﻿using CnBlogsCore.Model;
using MvvmHelpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using CnBlogsClient.Interface;

namespace CnBlogsClient.ViewModels
{
    class NewsDetailsViewModel : BaseViewModel
    {
        private NewsDetail news;

        public NewsDetailsViewModel(NewsDetail news)
        {
            this.news = news;
        }

        bool hasError;

        public bool HasError
        {
            get
            {
                return hasError;
            }

            set
            {
                SetProperty(ref hasError, value);
            }
        }

        public async Task<NewsDetail> RefreshNewsAsync()
        {
            try
            {
                IsBusy = true;
                HasError = false;

                string result = "";
                await Task.Run(() =>
                {
                    result = DependencyService.Get<INewsService>().GetNewsDetail(news.Id);
                });

                if (result.Length > 0)
                {
                    news.Body = result;
                    HasError = false;
                }
                else
                {
                    HasError = true;
                }
            }
            catch (Exception)
            {
                HasError = true;
            }
            finally
            {
                IsBusy = false;
            }

            return news;
        }
    }
}
